package cn.stylefeng.guns.modular.business.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.stylefeng.guns.modular.business.comment.YunHeKey;
import cn.stylefeng.guns.modular.business.entity.FigureInfo;
import cn.stylefeng.guns.modular.business.entity.SubDic;
import cn.stylefeng.guns.modular.business.entity.SubFileInfo;
import cn.stylefeng.guns.modular.business.enums.FigureInfoExceptionEnum;
import cn.stylefeng.guns.modular.business.mapper.FigureInfoMapper;
import cn.stylefeng.guns.modular.business.pojo.FigureInfoRequest;
import cn.stylefeng.guns.modular.business.pojo.SubFileInfoRequest;
import cn.stylefeng.guns.modular.business.service.FigureInfoService;
import cn.stylefeng.guns.modular.business.service.SubFileInfoService;
import cn.stylefeng.guns.modular.business.service.SubUseBrowseService;
import cn.stylefeng.roses.kernel.auth.api.LoginUserApi;
import cn.stylefeng.roses.kernel.auth.api.pojo.login.LoginUser;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.roses.kernel.rule.util.HttpServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 人物基本信息业务实现层
 *
 * @author zhangyaowen
 * @date 2021/10/25 16:46
 */
@Service
public class FigureInfoServiceImpl extends ServiceImpl<FigureInfoMapper, FigureInfo> implements FigureInfoService {

    @Resource
    private SubFileInfoService subFileInfoService;
    @Resource
    private SubUseBrowseService subUseBrowseService;
    @Resource
    private LoginUserApi loginUserApi;
	@Override
    public void add(FigureInfoRequest figureInfoRequest) {
        FigureInfo figureInfo = new FigureInfo();
        BeanUtil.copyProperties(figureInfoRequest, figureInfo);
        this.save(figureInfo);
    }

    @Override
    public void del(FigureInfoRequest figureInfoRequest) {
        FigureInfo figureInfo = this.queryFigureInfo(figureInfoRequest);
        this.removeById(figureInfo.getId());
    }

    @Override
    public void edit(FigureInfoRequest figureInfoRequest) {
        FigureInfo figureInfo = this.queryFigureInfo(figureInfoRequest);
        BeanUtil.copyProperties(figureInfoRequest, figureInfo);
        this.updateById(figureInfo);
    }

    @Override
    public FigureInfo detail(FigureInfoRequest figureInfoRequest) {
        return this.queryFigureInfo(figureInfoRequest);
    }

    @Override
    public PageResult<Map<String, Object>> findPage(String year,String value) {
        String[] years = {};
        if(!year.equals("") ) {
            years = StrUtil.splitToArray(year, ";");
        }
        LambdaQueryWrapper<FigureInfo> wrapper = createWrapperes(years,value);
        Page<FigureInfo> sysRolePage = this.page(PageFactory.defaultPage(), wrapper);

        PageResult<FigureInfo> projectSciencePageResult =  PageResultFactory.createPageResult(sysRolePage);
        List<FigureInfo> list = projectSciencePageResult.getRows();
        PageResult<Map<String, Object>> pageResult = new PageResult<>();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for(FigureInfo figureInfo : list){
            Map<String, Object> map = new HashMap<String, Object>();
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
            String jmid = YunHeKey.RWGS+figureInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            map.put("title",figureInfo.getFigureName());
            //获取人物图片
            SubFileInfoRequest subFileInfoRequest = new SubFileInfoRequest();
            subFileInfoRequest.setFileType(1L);//文件类型为图片
            subFileInfoRequest.setFileOriginName(figureInfo.getFigureName());
            subFileInfoRequest.setFileFirstBelong(YunHeKey.YHRW);
            List<SubFileInfo> subFileInfoPageResult = subFileInfoService.findIndexId(subFileInfoRequest);
            if(!subFileInfoPageResult.isEmpty()) {
                map.put("fileId", subFileInfoPageResult.get(0).getId());
            }else {
                SubFileInfoRequest subFileInfoRequestNo = new SubFileInfoRequest();
                subFileInfoRequestNo.setFileType(1L);
                subFileInfoRequestNo.setFileOriginName(YunHeKey.UNIMG);
                subFileInfoRequestNo.setFileFirstBelong(YunHeKey.UN);
                List<SubFileInfo> subFileInfoPageResultNo = subFileInfoService.findIndexId(subFileInfoRequestNo);
                map.put("fileId", subFileInfoPageResultNo.get(0).getId());
            }
            map.put("figureBirth",figureInfo.getFigureBirth());
            map.put("figureDeath",figureInfo.getFigureDeath());
            mapList.add(map);
        }
        pageResult.setRows(mapList);
        pageResult.setPageNo(projectSciencePageResult.getPageNo());
        pageResult.setTotalRows(projectSciencePageResult.getTotalRows());
        pageResult.setPageSize(projectSciencePageResult.getPageSize());
        pageResult.setTotalPage(projectSciencePageResult.getTotalPage());
        return pageResult;
    }


    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<FigureInfo> createWrapperes( String[] years, String value) {
        LambdaQueryWrapper<FigureInfo> queryWrapper = new LambdaQueryWrapper<FigureInfo>();
        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(value), FigureInfo::getFigureName, value).or()
                .like(ObjectUtil.isNotNull(value), FigureInfo::getFigureBeiming, value).or()
                .like(ObjectUtil.isNotNull(value), FigureInfo::getFigureOldnative, value).or()
                .like(ObjectUtil.isNotNull(value), FigureInfo::getFigureSecond, value).or()
                .like(ObjectUtil.isNotNull(value), FigureInfo::getFigureNewnative, value));
        if( years.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < years.length; i++) {
                    String time = years[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), FigureInfo::getFigureSecond, time);
                    if (i != years.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper;//.orderByDesc(FigureInfo::getHistoryDating);
    }


    @Override
    public List<FigureInfo> findList(FigureInfoRequest figureInfoRequest) {
        LambdaQueryWrapper<FigureInfo> wrapper = this.createWrapper(figureInfoRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    private FigureInfo queryFigureInfo(FigureInfoRequest figureInfoRequest) {
        FigureInfo figureInfo = this.getById(figureInfoRequest.getId());
        if (ObjectUtil.isEmpty(figureInfo)) {
            throw new ServiceException(FigureInfoExceptionEnum.FIGUREINFO_NOT_EXISTED);
        }
        return figureInfo;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/10/25 16:46
     */
    private LambdaQueryWrapper<FigureInfo> createWrapper(FigureInfoRequest figureInfoRequest) {
        LambdaQueryWrapper<FigureInfo> queryWrapper = new LambdaQueryWrapper<>();

        Long id = figureInfoRequest.getId();
        String figureSecond = figureInfoRequest.getFigureSecond();
        String secondCode = figureInfoRequest.getSecondCode();
        String figureId = figureInfoRequest.getFigureId();
        String figureName = figureInfoRequest.getFigureName();
        String figureBirth = figureInfoRequest.getFigureBirth();
        String figureDeath = figureInfoRequest.getFigureDeath();
        String figureBeiming = figureInfoRequest.getFigureBeiming();
        String figureOldnative = figureInfoRequest.getFigureOldnative();
        String figureNewnative = figureInfoRequest.getFigureNewnative();
        String figureDynasty = figureInfoRequest.getFigureDynasty();
        String figureLabel = figureInfoRequest.getFigureLabel();
        String figureIntroduction = figureInfoRequest.getFigureIntroduction();
        String figureAnnotation = figureInfoRequest.getFigureAnnotation();
        String historyPeriod = figureInfoRequest.getHistoryPeriod();
        String figureLaiyuanzhishu = figureInfoRequest.getFigureLaiyuanzhishu();
        Long figureZhishupage = figureInfoRequest.getFigureZhishupage();

        queryWrapper.eq(ObjectUtil.isNotNull(id), FigureInfo::getId, id);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureSecond), FigureInfo::getFigureSecond, figureSecond);
        queryWrapper.like(ObjectUtil.isNotEmpty(secondCode), FigureInfo::getSecondCode, secondCode);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureId), FigureInfo::getFigureId, figureId);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureName), FigureInfo::getFigureName, figureName);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureBirth), FigureInfo::getFigureBirth, figureBirth);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureDeath), FigureInfo::getFigureDeath, figureDeath);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureBeiming), FigureInfo::getFigureBeiming, figureBeiming);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureOldnative), FigureInfo::getFigureOldnative, figureOldnative);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureNewnative), FigureInfo::getFigureNewnative, figureNewnative);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureDynasty), FigureInfo::getFigureDynasty, figureDynasty);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureLabel), FigureInfo::getFigureLabel, figureLabel);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureIntroduction), FigureInfo::getFigureIntroduction, figureIntroduction);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureAnnotation), FigureInfo::getFigureAnnotation, figureAnnotation);
        queryWrapper.like(ObjectUtil.isNotEmpty(historyPeriod), FigureInfo::getHistoryPeriod, historyPeriod);
        queryWrapper.like(ObjectUtil.isNotEmpty(figureLaiyuanzhishu), FigureInfo::getFigureLaiyuanzhishu, figureLaiyuanzhishu);
        queryWrapper.eq(ObjectUtil.isNotNull(figureZhishupage), FigureInfo::getFigureZhishupage, figureZhishupage);

        return queryWrapper;
    }

    @Override
    public List<Map<String, Object>> toReview(String jmId) {
        byte[] key =YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);
        String decryptStr = aes.decryptStr(jmId, CharsetUtil.CHARSET_UTF_8);
        //获取ID字符串YHSJ后面真实的的id
        String id = StrUtil.subAfter(decryptStr,YunHeKey.RWGS,false);
        HttpServletRequest request = HttpServletUtil.getRequest();
        Long userid;
        if (ObjectUtil.isNotNull(request)) {
            LoginUser loginUser = loginUserApi.getLoginUser();
            userid = loginUser.getUserId();
        } else {
            throw new ServiceException(FigureInfoExceptionEnum.REQUEST_EMPTY);
        }
        LambdaQueryWrapper<FigureInfo> queryWrapper = new LambdaQueryWrapper<>();
        if ("".equals(id)) {
            List<Map<String, Object>> mapLists = new ArrayList<>();
//            Map<String, Object> map =new HashMap<>();
//            map.put("error","id为空");
            return mapLists;
        }
        queryWrapper.eq(ObjectUtil.isNotEmpty(id), FigureInfo::getId, id);
        List<FigureInfo> figureInfoList = this.list(queryWrapper);
        if(userid != 0l && userid != -1l) {
            subUseBrowseService.saveBrowse(YunHeKey.YHRW,figureInfoList.get(0).getFigureName(),userid,request);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (FigureInfo figureInfo : figureInfoList) {

            Map<String, Object> map = new HashMap<String, Object>();
            map = JSONObject.parseObject(JSONObject.toJSONString(figureInfo), Map.class);

            // 获取类的属性
            Field[] declaredFields = FigureInfo.class.getDeclaredFields();
            List<Map<String, Object>> mplist = new ArrayList<>();
            // 遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
            if (declaredFields.length != 0) {
                String title ="";
                int i = 1;
                Map<String, Object> p = new HashMap<String, Object>();
                for (Field field : declaredFields) {

                    Map<String, Object> mp = new HashMap<String, Object>();
                    if (field.getAnnotation(ApiModelProperty.class) != null) {
                        //获取注解属性
                        ApiModelProperty aa = field.getAnnotation(ApiModelProperty.class);
                        // key和value可根据需求存
                        // 这存的key为注解的值，value为类属性名
                        if("figureName".equals(field.getName()) || "figureIntroduction".equals(field.getName()) || "figureAnnotation".equals(field.getName()) ) {
                            if("figureAnnotation".equals(field.getName())) {
                                p.put(field.getName(), map.get(field.getName()));
                            }else{
                                p.put(field.getName(), map.get(field.getName()));
                            }
                        }else {
                            mp.put("key", aa.value());
                            mp.put("value", map.get(field.getName()));

                            if (i != 1) {
                                mplist.add(mp);
                            }
                        }

                    }
                    i++;
                }
                p.put("list", mplist);
                if (i != 1) {
                    mapList.add(p);
                }
            }
        }
        return mapList;
    }

    @Override
    public List<Map<String,Object>> findAllList(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<FigureInfo> wrapper = createWrapperByTown(riverList,townList,times,name);
        List<FigureInfo>  list = this.list(wrapper);
        List<Map<String,Object>> mapList=new ArrayList<>();
        for(FigureInfo figureInfo:list) {
            Map<String, Object> map = new HashMap<String, Object>();

            map.put("title", figureInfo.getFigureName());
            map.put("historyDating",figureInfo.getHistoryPeriod());
            map.put("theCommon","");
            map.put("from",figureInfo.getFigureLaiyuanzhishu() );
            map.put("createTime", DateUtil.format(figureInfo.getCreateTime(), "yyyy-MM-dd"));
            map.put("type",YunHeKey.RWGS);
            byte[] key = YunHeKey.PASSWORD.getBytes(StandardCharsets.UTF_8);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

            String jmid = YunHeKey.RWGS+figureInfo.getId();
            String encryptHex = aes.encryptHex(jmid);
            map.put("id",encryptHex);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 创建查询wrapper
     *
     * @author zhangyaowen
     * @date 2021/08/30 10:17
     */
    private LambdaQueryWrapper<FigureInfo> createWrapperByTown(List<SubDic> riverList, List<SubDic> townList, String[] times, String name) {
        LambdaQueryWrapper<FigureInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.and(i-> i.like(ObjectUtil.isNotNull(name), FigureInfo::getFigureName, name).or()
                .like(ObjectUtil.isNotNull(name), FigureInfo::getHistoryPeriod, name).or()
                .like(ObjectUtil.isNotNull(name), FigureInfo::getFigureLaiyuanzhishu, name).or()
                .like(ObjectUtil.isNotNull(name), FigureInfo::getFigureBeiming, name).or());

        if( !townList.isEmpty()) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < townList.size(); i++) {
                    String dicZname = townList.get(i).getDicZname();
                    wrapper.like(ObjectUtil.isNotEmpty(dicZname), FigureInfo::getFigureNewnative, dicZname);
                    if (i != townList.size() - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        if( times.length !=0) {
            queryWrapper.and(wrapper -> {
                for (int i = 0; i < times.length; i++) {
                    String time = times[i];
                    wrapper.like(ObjectUtil.isNotEmpty(time), FigureInfo::getFigureDynasty, time);
                    if (i != times.length - 1) {
                        wrapper.or();
                    }
                }
            });
        }
        return queryWrapper;
    }
    
    
    
}